package com.chinasolf.yygh.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chinasoft.enums.AuthStatusEnum;
import com.chinasoft.model.user.Patient;
import com.chinasoft.model.user.UserInfo;
import com.chinasoft.vo.user.LoginVo;
import com.chinasoft.vo.user.UserAuthVo;
import com.chinasoft.vo.user.UserInfoQueryVo;
import com.chinasolf.exception.YyghException;
import com.chinasolf.utils.JwtHelper;
import com.chinasolf.yygh.user.mapper.UserInfoMapper;
import com.chinasolf.yygh.user.service.PatientService;
import com.chinasolf.yygh.user.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2022-03-24
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private PatientService patientService;
    //用户登录的方法（手机）
    @Override
    public Map<String, Object> loginUser(LoginVo loginVo) {
        //1.获取手机号和验证码
        String phone = loginVo.getPhone();//手机号
        String code = loginVo.getCode();//验证码
        //2.非空判断
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
            throw new YyghException(20001, "登录参数为空");
        }
        //3.验证码校验
        //从redis根据手机号验证码
        String redisCode = redisTemplate.opsForValue().get(phone);

        //获取输入的验证码
        //用redis比较
        if (!code.equals(redisCode)) {
            throw new YyghException(20001, "验证码校验失败");
        }

        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(openid)) {
            //4.根据输入的手机号查询数据库，手机号是否第一次登录
            QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
            wrapper.eq("phone", phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            //4.1如果手机号第一次登录，把手机号信息添加数据库，完成注册
            if (userInfo == null) {
                userInfo = new UserInfo();
                userInfo.setName("");
                userInfo.setPhone(phone);
                userInfo.setStatus(1);//用户状态正常
                baseMapper.insert(userInfo);
            }


            //5.判断用户是否被禁用
            if (userInfo.getStatus() == 0) {
                throw new YyghException(20001, "用户已经被禁用");
            }

            //7.返回，需要的数据
            Map<String, Object> map =  this.get(userInfo);

            return map;
        } else {
            //1.根据绑定手机好查询，表是否存在和绑定手机号相同
            QueryWrapper<UserInfo> wrapperPhone = new QueryWrapper<>();
            wrapperPhone.eq("phone",phone);
            UserInfo userInfoPhone = baseMapper.selectOne(wrapperPhone);

            //1.1如果表不存在，直接更新微信手机号
            if (userInfoPhone == null){
                UserInfo userInfoWx = this.selectUserByOpenid(openid);
                if (userInfoWx == null){
                    throw  new YyghException(20001,"微信信息不存在");
                }
                userInfoWx.setPhone(phone);
                baseMapper.updateById(userInfoWx);


                //7.返回，需要的数据
                Map<String, Object> map =  this.get(userInfoWx);

                return map;
            }else{
                //1.2如果表存在相同手机号
                //把相同手机号数据查询出来
                UserInfo userInfoWx = this.selectUserByOpenid(openid);
                userInfoWx.setPhone(userInfoPhone.getPhone());
                //用户真实姓名
                userInfoWx.setName(userInfoPhone.getName());
                userInfoWx.setCertificatesType(userInfoPhone.getCertificatesType());
                userInfoWx.setCertificatesNo(userInfoPhone.getCertificatesNo());
                userInfoWx.setCertificatesUrl(userInfoPhone.getCertificatesUrl());
                //认证状态
                userInfoWx.setAuthStatus(userInfoPhone.getAuthStatus());
                //更新到微信里面
                //手机号数据删除
                QueryWrapper<UserInfo> wrapperDelete = new QueryWrapper<>();
                wrapperDelete.eq("phone",phone);
                baseMapper.delete(wrapperDelete);
                baseMapper.updateById(userInfoWx);
                //7.返回，需要的数据
                Map<String, Object> map =  this.get(userInfoWx);

                return map;
            }

        }
    }
    private Map<String,Object> get(UserInfo userInfo) {
        //返回页面显示名称
        Map<String, Object> map = new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        //根据userid和name生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }


    @Override
    public UserInfo selectUserByOpenid(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }
        //用户认证的方法
    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        userInfo.setName(userAuthVo.getName());
        //其他认证信息
        userInfo.setCertificatesType(userAuthVo.getCertificatesType());
        userInfo.setCertificatesNo(userAuthVo.getCertificatesNo());
        userInfo.setCertificatesUrl(userAuthVo.getCertificatesUrl());
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPageUser(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //调用方法分页条件查询
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间

        //对条件值进行非空判断
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(name)) {
            wrapper.like("name",name);
        }
        if(!StringUtils.isEmpty(status)) {
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper的方法
        IPage<UserInfo> pageModel = baseMapper.selectPage(pageParam, wrapper);
        //编号变成对应值封装
        pageModel.getRecords().stream().forEach(item -> {
            this.packageUserInfo(item);
        });
        return pageModel;
    }
    //用户锁定
    @Override
    public void lock(Long userId, Integer status) {
        if(status == 0||status == 1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }
    }
    //用户详情
    @Override
    public Map<String, Object> showUser(Long userId) {
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        List<Patient> patientList = patientService.findAllUserId(userId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("userInfo",userInfo);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if(authStatus.intValue()==2 || authStatus.intValue()==-1) {
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }
    }

    private UserInfo packageUserInfo(UserInfo userInfo) {
        //处理认证状态编码
        userInfo.getParam().put("authStatusString",AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));
        //处理用户状态 0  1
        String statusString = userInfo.getStatus().intValue()==0 ?"锁定" : "正常";
        userInfo.getParam().put("statusString",statusString);
        return userInfo;
    }
}
